package net.data;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

public class AskNamesResponse
{
	private Map<String, String> peers;
	private String fromAddress;
	
	public AskNamesResponse(String jsonResponse, String fromAddress)
	{
		Gson gson = new Gson();
		
		Type listType = new TypeToken<List<List<String>>>() {}.getType();

		peers = new HashMap<String, String>();
		this.fromAddress = fromAddress;
		
		try
		{
			List<List<String>> list = gson.fromJson(jsonResponse, listType);
			
			Iterator<List<String>> iter = list.iterator();
			
			while(iter.hasNext())
			{
				List<String> data = iter.next();
				if(data.size() != 2) throw new JsonSyntaxException("Incorrect syntax");
				else peers.put(data.get(0), data.get(1));
			}
		}
		catch(JsonSyntaxException ex)
		{
			peers = null;
		}
		catch(NullPointerException ex)
		{
			peers = null;
		}
	}
	
	public boolean isValid()
	{
		if(peers != null) return true;
		else return false;
	}
	
	public Map<String, String> getPeers()
	{
		return peers;
	}
	
	public String getFromAddress()
	{
		return fromAddress;
	}
}
